<?php
	session_start();
	include("progra_php_weekend/conexion.php"); 
	if (isset($_SESSION['idu'])) {
		header("location: weekend.php");
	}
	if(isset($_POST['registrarme']))
	    { 
	    	$correo = strtoupper($_POST['correo']);
			$nick1 = strtoupper($_POST['nick']);
	        $errors = array(); // declaramos un array para almacenar los errores
	        if(($correo == '') or (!preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/",$_POST['correo']))){
	            $errors[1] = "<span class='error'>Ingrese un email correcto</span>";
	        }else if($_POST['nombre'] == ''){
	            $errors[2] = "<span class='error'>Ingrese su nombre</span>";
	        }else if(($_POST['nick'] == '') or (preg_match("/ADMIN/",$nick1)) or (preg_match("/PORTALWEEKEND/",$nick1))){
	            $errors[3] = "<span class='error'>Ingrese un nick valido</span>";
	        }else if(($_POST['pass1'] == '') or ($_POST['pass1'] != $_POST['pass2'])){
	            $errors[4] = "<span class='error'>Las contraseñas no coinciden</span>";
	        }else if(($_POST['fechaD'] == '') or ($_POST['fechaM'] == '')or ($_POST['fechaA']=='')){
	            $errors[5] = "<span class='error'>Ingrese una fecha valida</span>";
	        }else if(($_POST['fechaD'] > 31 ) or ($_POST['fechaD'] < 1 ) or ($_POST['fechaM'] > 12 ) or ($_POST['fechaM'] < 1 )){
					$errors[5] = "<span class='error'>Ingrese una fecha valida</span>";
	        }else if(($_POST['fechaA'])>1900) {
	        	$f = $_POST['fechaA']."-".$_POST['fechaM']."-".$_POST['fechaD'];
	    		$dias = explode("-", $f,3);
				$dias = mktime(0,0,0,$dias[1],$dias[2],$dias[0]);
				$edad = (int)((time()-$dias)/31556926 );
	            if ($edad<15)
	            	$errors[6] = "<span class='error'>debes tener por lo menos 15 años para acceder</span>";
		    }else $errors[5] = "<span class='error'>Ingrese una fecha valida</span>";
		    if(!isset($_POST['terminos']))
            	$errors[7] = "<span class='error2'>Debes aceptar los terminos y condiciones</span>";
	        $er = sizeof($errors);
	        if ($er==0 )
	        {
	        	$nick = $_POST['nick'];
					$nom = $_POST['nombre'];
					$contr =crypt( $_POST['pass1'],'portalweekend');
					$ciudad = $_POST['ciudad'];
					$genero = $_POST['genero'];
					//convierto la fecha del servidor para almacenarla en la base de datos
					$fecha = date("Y-m-d",strtotime($f));
					$con=mysql_connect($host,$user,$passw) or die("Error de conección");
					mysql_select_db($db,$con) or die("Error en la Base de datos");
					$verifica_correo = mysql_query("SELECT idusuario FROM usuario WHERE correo='$correo'",$con);
					$res = mysql_fetch_assoc($verifica_correo);
					if ($res['idusuario'] == null)
					{
						$existe = mysql_query("SELECT idusuario FROM usuario WHERE nick='$nick'",$con);
						$res2 = mysql_fetch_assoc($existe);	
						if ($res2['idusuario'] == null)
						{
							if ($genero=="Hombre") {
								$imagen='imagenes/usuarios/genero_m.jpg';
								$imagen2='imagenes/vista_previa/genero_m.jpg';
							}
							else {
								$imagen='imagenes/usuarios/genero_f.jpg';
								$imagen2='imagenes/vista_previa/genero_f.jpg';	
							}
							mysql_query("INSERT INTO usuario (nombre, correo, pass, fecha_nac, pais, ciudad, foto_perfil,foto_miniatura,genero,nick,habilitado) VALUES ('$nom', '$correo', '$contr', '$fecha', 'Guatemala','$ciudad','$imagen','$imagen2 ','$genero','$nick',1)",$con) or die("Error: ". mysql_error());
							$verifica_nick = mysql_query("SELECT idusuario,nick,ciudad FROM usuario WHERE correo='$correo'",$con);
							$res = mysql_fetch_assoc($verifica_nick);
							$fecha_servidor = date("Y-m-d H:i");
							$nuevafecha_servidor = strtotime('+1 hour',strtotime( $fecha_servidor));
							$fecha_servidor = date ( 'Y-m-d H:i' , $nuevafecha_servidor);
							$_SESSION['idu'] = $res['idusuario'];
							$_SESSION['nick'] = $res['nick'];
							$_SESSION['ciudad']=$ciudad;
							$cambio = "Nuevo usuario en PortalWeekend, Bienvenido ".$nick;
							mysql_query("INSERT INTO log_actividad (tipo,cambio,fecha,id_usuario) VALUES ('NU','$cambio','$fecha_servidor','$_SESSION[idu]')",$con) or die("Error: ". mysql_error());
							session_write_close();
							//----------------- codigo para aparecer conectado -----------------------
			                $session=$_SESSION['idu'];
			                $time=time();
			                $time_check=$time-60;//tiempo de 1 minuto
			                $resultado=mysql_query("SELECT * FROM online WHERE usuario='$session'",$con);
			                if ($resultado== null)
			                    $count = 0;
			                else
			                    $count=mysql_num_rows($resultado);
			            
			                if($count==0)
			                {
			                    mysql_query("INSERT INTO online (usuario, fecha) VALUES('$session', '$time')",$con) or die("error cuando es 0".mysql_error());
			                }
			                else 
			                {
			                    $resultado2=mysql_query("UPDATE online SET fecha='$time' WHERE usuario = '$session'",$con) or die("error cuando es 0");
			                }
			                $resultado3=mysql_query("SELECT * FROM online",$con);
			                $contar_online=mysql_num_rows($resultado3);
			                //echo "Usuarios en linea : $contar_online";
			                //se elimina a los que ya tengan tiempo de no actualizar
			                $result4=mysql_query("DELETE FROM online WHERE fecha<$time_check");
			                //.............................................................................................
							mysql_close();
							header("Location: weekend.php");
						}
						else
							$errors[3] = "<span class='error'>Nick ya en uso</span>";
					}
					else
					{
						$errors[1] = "<span class='error'>Correo ya registrado</span>";
					}
	        }
	    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link rel="icon" href="imagenes_referencia_pag/logo2_ico.ico" type="image/x-icon" />
		<link rel="stylesheet" href="desing_css_weekend/index_general.css"/>
		<script src="librerias_y_codigo_jp/jquery-1.9.1.js"></script>
		<title>:: Bienvenido PortalWeekend ::</title>
		<script type='text/javascript'>
			function activar() {
				document.getElementById('log_fail').style.display='block'; }
		</script>
	</head>
	<body>


	<!-- Script facebook-->
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
  FB.init({
    appId      : '227515064066084', // App ID
    channelUrl : '//www.portalweekend.com/channel.html', // Channel File
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });

  // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
  // for any authentication related change, such as login, logout or session refresh. This means that
  // whenever someone who was previously logged out tries to log in again, the correct case below 
  // will be handled. 
  FB.Event.subscribe('auth.authResponseChange', function(response) {
    // Here we specify what we do with the response anytime this event occurs. 
    if (response.status === 'connected') {
      // The response object is returned with a status field that lets the app know the current
      // login status of the person. In this case, we're handling the situation where they 
      // have logged in to the app.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // In this case, the person is logged into Facebook, but not into the app, so we call
      // FB.login() to prompt them to do so. 
      // In real-life usage, you wouldn't want to immediately prompt someone to login 
      // like this, for two reasons:
      // (1) JavaScript created popup windows are blocked by most browsers unless they 
      // result from direct interaction from people using the app (such as a mouse click)
      // (2) it is a bad experience to be continually prompted to login upon page load.
      FB.login();
    } else {
      // In this case, the person is not logged into Facebook, so we call the login() 
      // function to prompt them to do so. Note that at this stage there is no indication
      // of whether they are logged into the app. If they aren't then they'll see the Login
      // dialog right after they log in to Facebook. 
      // The same caveats as above apply to the FB.login() call here.
      FB.login();
    }
  });
  };

  // Load the SDK asynchronously
  (function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src = "//connect.facebook.net/en_US/all.js";
   ref.parentNode.insertBefore(js, ref);
  }(document));

  // Here we run a very simple test of the Graph API after login is successful. 
  // This testAPI() function is only called in those cases. 
  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Good to see you, ' + response.name + '.');
    });
  }
</script>

<!--
  Below we include the Login Button social plugin. This button uses the JavaScript SDK to
  present a graphical Login button that triggers the FB.login() function when clicked.

  Learn more about options for the login button plugin:
  /docs/reference/plugins/login/ -->

<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>








		<div id="pagina_inicio">
			<img src="imagenes_referencia_pag/portalWeekend.png">
			<div id="informacion">
				<div id="Login">
				<label class="titulo">Ingresa al sitio</label>
					<form action="progra_php_weekend/login.php" name="f_login" method="post" enctype="multipart/form-data">

	                	<div class="log">
	                		<label>Correo E.:</label>
							<input name="correo" type="text" size="35"/>
							
						</div><br>
						<div class="log">
							<label>Contraseña:</label>
							<input name="pass" type="password" size="30"/>
						</div><br>
						<?php
							if (isset($_GET['log']))
							{
								echo "
									<div id='log_fail'>
										<label>¡Usuario o Clave incorrecta! </label>
									</div>";
							}
						?>
						<input type="submit" value="Ingresar" class="botonazo"/>
	                </form >
				</div>
			</div><br>

			<script language="javascript">
			function nick_name() 
				{
					var entrada  = document.getElementById('nick').value;
			                var dataString = 'nuevo='+ entrada;
			                  $.ajax({
			                    type: "POST",
			                    url: "progra_php_weekend/verificar.php",
			                    data: dataString,
			                    success: function(blog) {
			                        document.getElementById("label_nick").style.color= blog;
			                    }
			                  });
			                  return false;
				}
			</script>
			<div id="derechos">Todos los derechos reservados. 2013 <br><span>info@portalweekend.com</span></div>
		</div>
	</body>
</html>